#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/7/23 18:42
# @Author  : youfeng

import click
from flask import Flask, request, jsonify

from ext.proxy_service import ProxyService
from logger import AppLogger

log = AppLogger('gateway_proxy_server.log').get_logger()

app = Flask(__name__)

proxy_service = ProxyService(log)


@app.route('/')
def index():
    return "proxy server is working!"


@app.route("/proxy", methods=['GET'])
def get_proxy():
    tag = request.args.get("tag")
    host = request.args.get("host")
    if tag is None:
        result = {"status": "fail", "msg": "tag param is missing"}
        return jsonify(result)

    if host is None:
        result = {"status": "fail", "msg": "host param is missing"}
        return jsonify(result)

    proxy = proxy_service.get_proxy(host, tag)
    if proxy is None:
        result = {"status": "fail"}
        log.info("当前访问: tag = {} host = {} result = fail".format(tag, host))
    else:
        result = {"status": "ok", "proxy": proxy}
        log.info("当前访问: tag = {} host = {} result = ok proxy = {}".format(tag, host, proxy))
    return jsonify(result)


@click.command()
@click.option('--port',
              type=int,
              default=9600,
              help='新版工商数据同步到旧工商库')
def main(port):
    log.info("启动代理服务...")
    app.run(host='0.0.0.0', port=port, threaded=False)
    # app.run(port=port, threaded=False)


if __name__ == '__main__':
    main()
